import { Component, ViewChild, Injector, Output, 
    EventEmitter, ElementRef , Input , OnInit } from '@angular/core';

import { RoleServiceProxy, RoleEditDto, CreateOrUpdateRoleInput } from '@shared/service-proxies/service-proxies';
import {AppComponentBase} from '@shared/app-component-base';

import { NzModalSubject, NzModalService, NzMessageService } from 'ng-zorro-antd';

import { PermissionTreeComponent } from './permission-tree.component';

import * as _ from 'lodash';

@Component({
    selector: 'createOrEditRoleModal',
    templateUrl: './create-or-edit-role-modal.component.html'
})
export class CreateOrEditRoleModalComponent extends AppComponentBase
implements OnInit {

    @ViewChild('permissionTree') permissionTree: PermissionTreeComponent;


    @Input() id?: number;

    active = false;
    saving = false;

    role: RoleEditDto = new RoleEditDto();
    constructor(
        injector: Injector,
        private _roleService: RoleServiceProxy,
        private subject: NzModalSubject
    ) {
        super(injector);
    }

    show(roleId?: number): void {
        const self = this;
        self.active = true;

        self._roleService.getRoleForEdit(roleId).subscribe(result => {
            self.role = result.role;
            this.permissionTree.editData = result;

        });
    }

    onShown(): void {
        
    }

    save(): void {
        const self = this;

        const input = new CreateOrUpdateRoleInput();
        input.role = self.role;
        input.grantedPermissionNames = self.permissionTree.getGrantedPermissionNames();

        this.saving = true;
        this._roleService.createOrUpdateRole(input)
            .finally(() => this.saving = false)
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.subject.destroy('onOk');
            });
    }

    close(): void {
        this.subject.destroy();
    }

    ngOnInit() {
        this.show(this.id);
    }
}
